package java_thinking.unit_21._21_2;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;

import javax.servlet.*;
import java.io.IOException;
import java.math.BigInteger;

/**
 * @Desc:   2-8
 * @author: cww
 * @DateTime: 2019/5/30 9:05
 */
@ThreadSafe
public class CacheFactorize implements Servlet {
    @GuardedBy("this") private BigInteger lastNumber;
    @GuardedBy("this") private BigInteger[] lastFactors;
    @GuardedBy("this") private long his;
    @GuardedBy("this") private long cacheHits;
    public synchronized long getHis() {
        return his;
    }
    public synchronized double getCacheHitRatio() {
        return (double) cacheHits / (double) his;
    }
    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        //位于同步代码块之外的
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        //负责保护判断是否只需返回缓存结果的操作序列，this指当前类
        synchronized (this) {
            ++his;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factor(i);
            //负责确保对缓存的数值和因数分解结果进行同步更新
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(resp, factors);
    }
    void encodeIntoResponse(ServletResponse resp, BigInteger[] factors) {
    }

    BigInteger extractFromRequest(ServletRequest req) {
        return new BigInteger("7");
    }

    BigInteger[] factor(BigInteger i) {
        // Doesn't really factor
        return new BigInteger[]{i};
    }
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
